#ifndef TMP_FILE_HPP
#define TMP_FILE_HPP

#include <string>
#include <sstream>

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <cstdlib>



class TmpFile{
    std::string m_filename;
public:
    TmpFile(size_t bytes_size){
        m_filename = createNew();
        prepare( bytes_size );
    }
    ~TmpFile(){
//        remove( m_filename.c_str() );
    }
    const std::string & filename() const{
        return m_filename;
    }
private:
    bool fileExists(const char * name ){
        // the file can still exists and we dont have read permissions
        FILE * f = fopen( name, "r" );
        if ( f ){
            fclose( f );
            return true;
        }
        return false;
    }
    std::string createNew(){
        std::string name;
        do{
            std::ostringstream oss;
            oss << "tmp" << rand();
            name = oss.str();
        }
        while( fileExists( name.c_str() ) );
        FILE * f = fopen( name.c_str(), "w" );
        if ( f ){
            fclose(f);
        }else{
            throw std::ios_base::failure( "TmpFile: Cannot create new file." );
        }
        return name;
    }
    void prepare( size_t size ){
        int fd = open(m_filename.c_str(),O_WRONLY);
        if ( ftruncate(fd, size) != 0 ){
            std::ostringstream oss;
            oss << "TmpFile(): some error occured: " << errno << std::endl;
            throw std::ios_base::failure( oss.str() );
        }
        close( fd );
    }
};

#endif // TMP_FILE_HPP
